﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using Microsoft.Win32;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Configuration;

namespace SQLServerDatabaseBackup
{
    public partial class frmRestore : DevExpress.XtraEditors.XtraForm
    {
        public frmRestore()
        {
            InitializeComponent();
        }
        public string ConnString { get; set; }
        Server srv;
        ServerConnection conn;
        Thread threadGetNetworkInstances;
        private void frmBackup_Load(object sender, EventArgs e)
        {

            ConnString = ConfigurationManager.ConnectionStrings["QLTV.Properties.Settings.CrewManagmentConnectionString"].ConnectionString;
            loadSimpleBackup();
            //
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
            String[] instances = (String[])rk.GetValue("InstalledInstances");
            if (instances.Length > 0)
            {
                foreach (String element in instances)
                {
                    if (element == "MSSQLSERVER")
                        lstLocalInstances.Items.Add(System.Environment.MachineName);
                    else
                        lstLocalInstances.Items.Add(String.Format(@"{0}\{1}", System.Environment.MachineName, element));
                }
            }
            threadGetNetworkInstances = new Thread(GetNetworkInstances);
            threadGetNetworkInstances.Start();
        }
        public void loadSimpleBackup()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnString);
            txtMayChu.EditValue = builder.DataSource;
            txtCSDL.EditValue = builder.InitialCatalog;
            txtTaiKhoan.EditValue = builder.UserID;
            txtMatKhau.EditValue = builder.Password;


        }
        public void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
        {

            //this.progressBar1.Value = e.Percent;
        }
        delegate void SetMessageCallback(string text);
        private void AddNetworkInstance(string text)
        {
            if (this.lstNetworkInstances.InvokeRequired)
            {
                SetMessageCallback d = AddNetworkInstance;
                this.BeginInvoke(d, new object[] { text });
            }
            else
            {
                this.lstNetworkInstances.Items.Add(text);
            }
        }
        private void GetNetworkInstances()
        {
            DataTable dt = SmoApplication.EnumAvailableSqlServers(false);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    AddNetworkInstance(dr["Name"].ToString());
                }
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            SaveFileDialog savefile = new SaveFileDialog();

            savefile.InitialDirectory = "D:\\";
            savefile.Filter = "bak files (*.bak)|*.txt|All files (*.*)|*.*";
            savefile.FilterIndex = 2;
            savefile.RestoreDirectory = true;

            if (savefile.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = savefile.FileName.ToString();

            }
        }

        private void buttonEdit1_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog saveFile = new OpenFileDialog();
            saveFile.InitialDirectory = "D:\\";
            saveFile.Filter = "BackUp files (*.bak)|*.bak|All files (*.*)|*.*";
            saveFile.FilterIndex = 0;
            saveFile.RestoreDirectory = true;

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                txtDuongDan.Text = saveFile.FileName.ToString();
            }
        }

        private void wizardControl1_NextClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
        {

            if (e.Page == pageWelcome)
            {
                if ((bool)radChoose.EditValue == false)
                {
                    wizardControl1.SelectedPage = pageSimple;
                }
            }
            if (e.Page == pageSimple)
            {
                wizardControl1.SelectedPage = pageComplete;
            }


        }

        private void wizardControl1_PrevClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
        {
            if (e.Page == pageAdvance)
            {
                wizardControl1.SelectedPage = pageWelcome;
            }
            if (e.Page == pageComplete)
            {
                if ((bool)radChoose.EditValue == true)
                {
                    wizardControl1.SelectedPage = pageAdvance;
                }
            }

        }

        private void frmBackup_FormClosed(object sender, FormClosedEventArgs e)
        {
            // threadGetNetworkInstances.Abort();
        }

        private void wizardControl1_FinishClick(object sender, CancelEventArgs e)
        {
            string info = "Dữ liệu hiện tại có thể bị mất!" + Environment.NewLine +
                        "Bạn có chắc chắn muốn tiếp tục?";
            if (XtraMessageBox.Show(info, "Cảnh báo",  MessageBoxButtons.OKCancel,MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {

                if ((bool)radChoose.EditValue == true)
                {
                    //simple
                    #region Connect
                    try
                    {
                        string sqlSErverInstance;
                        sqlSErverInstance = server;
                        conn = new ServerConnection(sqlSErverInstance, txtTaiKhoan.Text, txtMatKhau.Text);
                        srv = new Server(conn);
                        srv.KillAllProcesses(database);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                    }

                    #endregion
                    #region Restore

                    Restore res = new Restore();

                    this.Cursor = Cursors.WaitCursor;
                    //this.dataGridView1.DataSource = string.Empty;
                    try
                    {
                        string fileName = file;
                        string databaseName = database;

                        res.Database = databaseName;
                        res.Action = RestoreActionType.Database;
                        res.Devices.AddDevice(fileName, DeviceType.File);



                        // this.progressBar1.Value = 0;
                        //this.progressBar1.Maximum = 100;
                        // this.progressBar1.Value = 10;

                        //  res.PercentCompleteNotification = 10;
                        res.ReplaceDatabase = true;
                        // res.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);

                        res.SqlRestore(srv);
                        alertControl1.Show(this, "Phục hồi CSDL", String.Format("Phục hồi dữ liệu CSDL:  {0} thành công!", databaseName));
                        this.Close();
                    }
                    catch (SmoException exSMO)
                    {
                        MessageBox.Show(exSMO.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                        // this.progressBar1.Value = 0;
                    }
                    #endregion
                }
                else
                {
                    //Advance
                    #region Connect
                    try
                    {

                        if (chkWindowsAuthentication.Checked == true)
                        {
                            conn = new ServerConnection();
                            conn.ServerInstance = server;
                        }
                        else
                        {
                            conn = new ServerConnection(server, txtLogin.Text, txtPassword.Text);
                        }
                        srv = new Server(conn);
                        srv.KillAllProcesses(database);


                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                    }

                    #endregion
                    #region Restore

                    Restore res = new Restore();

                    this.Cursor = Cursors.WaitCursor;
                    //this.dataGridView1.DataSource = string.Empty;
                    try
                    {
                        string fileName = file;
                        string databaseName = database;

                        res.Database = databaseName;
                        res.Action = RestoreActionType.Database;
                        res.Devices.AddDevice(fileName, DeviceType.File);

                        //this.progressBar1.Value = 0;
                        //this.progressBar1.Maximum = 100;
                        //this.progressBar1.Value = 10;

                        //res.PercentCompleteNotification = 10;
                        res.ReplaceDatabase = true;
                        //res.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);
                        res.SqlRestore(srv);

                        alertControl1.Show(this, "Phục hồi CSDL", "Phục hồi dữ liệu CSDL:  " + databaseName + " thành công!");
                        this.Close();
                    }
                    catch (SmoException exSMO)
                    {
                        MessageBox.Show(exSMO.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                        // this.progressBar1.Value = 0;
                    }
                    #endregion
                }
            }
        }
        string server = "";
        string database = "";
        string file = "";
        private void wizardControl1_SelectedPageChanged(object sender, DevExpress.XtraWizard.WizardPageChangedEventArgs e)
        {

            if (e.Page == pageComplete)
            {

                if ((bool)radChoose.EditValue == true)
                {
                    server = txtMayChu.Text;
                    database = txtCSDL.Text;
                    file = txtDuongDan.Text;


                }
                else
                {

                    database = ddlDatabase.SelectedItem.ToString();
                    if (this.tabServers.SelectedIndex == 0)
                    {
                        server = lstLocalInstances.SelectedItem.ToString();
                    }
                    else
                    {
                        server = lstNetworkInstances.SelectedItem.ToString();
                    }
                    file = txtFileName.Text;

                }
                pageComplete.FinishText = "Thông tin sao lưu CSDL: " + Environment.NewLine + "- Máy chủ: " + server +
                                                                        Environment.NewLine + "- CSDL: " + database +
                                                                        Environment.NewLine + "- Đường dẫn: " + file;
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            try
            {
                ddlDatabase.Items.Clear();

                string sqlSErverInstance;

                if (this.tabServers.SelectedIndex == 0)
                {
                    sqlSErverInstance = lstLocalInstances.SelectedItem.ToString();
                }
                else
                {
                    sqlSErverInstance = lstNetworkInstances.SelectedItem.ToString();
                }

                if (chkWindowsAuthentication.Checked == true)
                {
                    conn = new ServerConnection();
                    conn.ServerInstance = sqlSErverInstance;
                }
                else
                {
                    conn = new ServerConnection(sqlSErverInstance, txtLogin.Text, txtPassword.Text);
                }
                srv = new Server(conn);

                foreach (Database db in srv.Databases)
                {
                    ddlDatabase.Items.Add(db.Name);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void txtFileName_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.InitialDirectory = "D:\\";
            openfile.Filter = "BackUp files (*.bak)|*.bak|All files (*.*)|*.*";
            openfile.FilterIndex = 0;
            openfile.RestoreDirectory = true;

            if (openfile.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = openfile.FileName.ToString();
            }
        }

        private void wizardControl1_SelectedPageChanging(object sender, DevExpress.XtraWizard.WizardPageChangingEventArgs e)
        {
            if (e.Direction == DevExpress.XtraWizard.Direction.Forward)
            {
                //if (e.Page == pageComplete)
                //    if (txtDuongDan.Text == "")
                //    {
                //        dxValidationProvider1.Validate();
                //        e.Cancel = true;
                //    }
                //if (e.Page == pageAdvance)
                //    if (txtFileName.Text == "")
                //    {
                //        dxValidationProvider1.Validate();
                //        e.Cancel = true;
                //    }
            }
        }

        private void wizardControl1_CancelClick(object sender, CancelEventArgs e)
        {
            this.Close();
        }


    }
}